package org.internna.ossmoney.mvc;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import static org.internna.ossmoney.util.SecurityUtils.*;

public final class MainInterceptor extends HandlerInterceptorAdapter {

	@Autowired private AuthenticationManager authenticationManager;

	public MainInterceptor() {
		this.standAlone = Boolean.parseBoolean(System.getProperty("ossmoney-standalone"));
	}

	private boolean standAlone = false;
	private String dojoLocation = "/resources";

	public void setDojoLocation(String location) {
		this.dojoLocation = location;
	}

	@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (standAlone && isAuthenticated()) {
			authenticate(authenticationManager, "admin", "admin");
		}
		return super.preHandle(request, response, handler);
	}

	@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if (modelAndView != null) {
			Map<String, Object> model = modelAndView.getModel(); 
			model.put("standalone", standAlone);
			model.put("dojoLocation", dojoLocation);
		}
		super.postHandle(request, response, handler, modelAndView);
	}

}
